package com.ruoyi.detection.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.detection.domain.DetectionLog;
import com.ruoyi.detection.domain.RiceCanopyDetectionLog;
import com.ruoyi.detection.domain.RiceCanopyRet;
import com.ruoyi.detection.mapper.RiceCanopyModelMapper;
import com.ruoyi.detection.service.RiceCanopyService;
import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseArray;
import com.ruoyi.utils.ParseString;
import com.ruoyi.ysVideo.mapper.EzvizMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: class by cxf
 * @author: AbrahamBill
 * @date: 2022/6/30
 **/
@Service
@Slf4j
public class RiceCanopyServiceImpl implements RiceCanopyService {
    @Autowired
    private RiceCanopyModelMapper riceCanopyModelMapper;

    @Autowired
    private EzvizMapper ezvizMapper;
    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.riceCanopyDetection}")
    private String riceDetectionUrl;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /** 调用水稻病害检测模型进行识别，并保存原图、检测结果图、缩略图*/
    @Override
    public List<RiceCanopyDetectionLog> insertRiceCanopyDetectionLog(MultipartFile file,String deviceSerial) throws IOException {
        // upload() : 返回的就是文件路径
        String images = FileUploadUtils.upload(RuoYiConfig.getRiceCanopyDetectionPath(), file);
        String detectionImages = StringUtils.substringAfter(images, "profile");
        /* 解析识别结果构造实例存入数据库并返回, 检测不需要list集合，识别有多个可能，需要集合装载，其他的不需要 */
        List<RiceCanopyDetectionLog> detectionLogList = new ArrayList<>();
        DetectionLog detectionLog = null;
        ImgDrawCircleTool tool = new ImgDrawCircleTool();
        try {
            // 图片发送到Django进行识别
            ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, riceDetectionUrl);
            log.info("responseEntity------->" + responseEntity.getBody());
            // json格式的数据转换成数组格式
            detectionLogList = JSON.parseArray(responseEntity.getBody(), RiceCanopyDetectionLog.class);
            log.info(detectionLogList.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        if (StringUtils.isNotNull(detectionLogList)&&detectionLogList.size()!=0) {
            for (RiceCanopyDetectionLog detection : detectionLogList) {
                if (StringUtils.isNotNull(detection)) {
                    System.out.println(detection.getCorner());
                    detection.setDeviceSerial(deviceSerial)
                            .setStrCorner(ParseArray.parseArrayList(detection.getCorner()))
                            .setImagePath(images)
                            .setOriginalFileName(file.getOriginalFilename())
                            .setThumPath(images.replace("original", "thum"))
                            .setResultPath(images.replace(".jpg","_Result.jpg"))
                            .setInsertTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                            .setCreateTime(getCreateTime(detection.getOriginalFileName()));
                    /*画框之后的结果图 resUrl  缩略图 已添加 */
                    List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                    // 将JSON字符串转换为Map对象
                    Map<String, Integer> resMap = JSON.parseObject(ParseString.getTagNum(detection.getTag()), Map.class);
                    if(resMap==null){
                        resMap = new HashMap<>();
                    }
                    String resultPath =tool.doDrawRectangle(detection.getCorner(),tagList,resMap,profile + detectionImages,ezvizMapper.selectVMDeviceName(deviceSerial)).replace(profile, Constants.RESOURCE_PREFIX);
                    // 需要把路径改到新resultPath
                    detection.setResultPath(resultPath.replace("__Result","_Result"));

                    detection.setTag(ParseString.getTagNum(detection.getTag()));
                    System.out.println(detection.toString());
                    System.out.println(detection.getCorner());
                    riceCanopyModelMapper.insertRiceCanopyDetectionLog(detection);
                }
            }
            return detectionLogList;
        }else{
            RiceCanopyDetectionLog detection = new RiceCanopyDetectionLog();
            detection.setDeviceSerial(deviceSerial)
                    .setStrCorner("")
                    .setImagePath(images)
                    .setOriginalFileName(file.getOriginalFilename())
                    .setThumPath(images.replace("original", "thum"))
                    .setResultPath(images.replace(".jpg","_Result.jpg"))
                    .setInsertTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                    .setCreateTime(getCreateTime(detection.getOriginalFileName()));
            String resultPath = tool.doDrawRectangle(new ArrayList<>(),new ArrayList<>(),new HashMap<>(), profile + detectionImages, ezvizMapper.selectVMDeviceName(deviceSerial)).replace(profile, Constants.RESOURCE_PREFIX);
            // 需要把路径改到新resultPath
            detection.setResultPath(resultPath.replace("__Result","_Result"));

            detection.setTag("{}");
            detectionLogList= new ArrayList<>();
            detectionLogList.add(detection);
            return detectionLogList;
        }
    }

    /** 返回已经抓取与识别的水稻病害图片*/
    public List<RiceCanopyRet> selectRiceCanopyResultImg(String deviceSerial){
        return  riceCanopyModelMapper.selectRiceCanopyResultImg(deviceSerial);
    }

        /**工具方法，用于获取特定图片的时间
         * 图片格式如：G45812906_2021_08_28_16_39_05.jpg
         * */
    private String getCreateTime(String fileName){
        try {
            String time_str = fileName.substring(10);
            String[] res = time_str.split("\\.")[0].split("_");
            String ret = "";
            for (int i = 0; i < res.length; i++) {
                if (i < 2) {
                    ret += res[i] + "-";
                } else if (i == 2) {
                    ret += res[i] + " ";
                } else if (i < 5) {
                    ret += res[i] + ":";
                } else {
                    ret += res[i];
                }
            }
            return ret;
        }catch (Exception e){
            return "0000-00-00 00:00:00";
        }

    }
}
